package com.yxx.service.impl;

import com.yxx.mapper.AddressBookMapper;
import com.yxx.medicinecommon.context.BaseContext;
import com.yxx.medicinepojo.entity.AddressBook;
import com.yxx.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author yuxiangxun
 * @date 2024/9/24
 * @apiNote
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 根据当前微信登录用户id查询其所有地址信息
     * @param addressBook
     * @return
     */
    @Override
    public List<AddressBook> addressBookList(AddressBook addressBook) {
        List<AddressBook> list =  addressBookMapper.addressBookList(addressBook);
        return list;
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void addAddressBook(AddressBook addressBook) {
        //获取当前微信登录用户id
        Long wx_user_id = BaseContext.getCurrentId();

        //将当前微信登录用户id封装到addressBook的userId属性中
        addressBook.setUserId(wx_user_id);

        //设置这个新增地址不是默认地址  封装addressBook对象中的isDefault属性为0
        addressBook.setIsDefault(0);

        //通过addressBook对象插入数据
        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据地址id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressBookById(Long id) {
        AddressBook addressBook = addressBookMapper.getAddressBookById(id);
        return addressBook;
    }

    /**
     * 修改地址信息
     * @param addressBook
     */
    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBookMapper.updateAddressBook(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteAddressBook(Long id) {
        addressBookMapper.deleteAddressBook(id);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    @Transactional
    public void setDefaultAddress(AddressBook addressBook) {
        //可能当前地址为默认地址，所以先把默认地址修改为0更新后，再修改为1更新

        //获取当前微信登录用户id
        Long wx_user_id = BaseContext.getCurrentId();

        //封装当前微信登录用户id到 addressBook 对象
        addressBook.setUserId(wx_user_id);

        //设置非默认地址状态为0 ,封装到addressBook对象 ，更新  -> 将当前用户的所有地址设置为非默认地址状态   根据用户id修改默认地址状态
        //update address_book set is_default = 0 where user_id = ?
        addressBook.setIsDefault(0);
        addressBookMapper.updateDefaultByUserId(addressBook);

        //再设置默认默认地址状态为1，封装到addressBook对象，更新  -》  将当前用户的一条记录设置为默认地址  根据地址id修改默认地址状态
        //update address_book set is_default = 1 where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.updateAddressBook(addressBook);
    }
}
